package com.d1711.zhanggm.springboot.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.d1711.zhanggm.springboot.entity.Classes;
import com.d1711.zhanggm.springboot.entity.ClassesVo;
import com.d1711.zhanggm.springboot.service.IClassesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 班级表 前端控制器
 * </p>
 *
 * @author 张国明
 * @since 2020-05-27
 */
@RestController
@RequestMapping("/classes")
//@CrossOrigin
public class ClassesController {

    @Autowired
    private IClassesService iClassesService;

    @GetMapping("listAll")
    public List<Classes> listAll(){
        return iClassesService.list();
    }

    /**
     * 保存班级信息
     * @param classes
     * @return
     */
    @PostMapping("save")
    public boolean save(@RequestBody Classes classes){
        boolean result = iClassesService.save(classes);
        return result;
    }

    /**
     * classesVo:{classesList:[{id:1,name:'1711d'}]}
     * @param classesVo
     * @return
     */
    @PostMapping("batchSave")
    public List<Classes> batchSave(@RequestBody ClassesVo classesVo){
        //班级数据
        List<Classes> classesList = classesVo.getClassesList();
        //班级的所有数据
        List<Classes> listAll = iClassesService.list();
        //数据库的所有数据
        //如果班级数据是空，删除所有班级数据
        if(classesList==null || classesList.size()==0){
            QueryWrapper queryWrapper = new QueryWrapper();
            iClassesService.remove(queryWrapper);
            return iClassesService.list();
        }
        //先删除数据
        /*QueryWrapper queryWrapper = new QueryWrapper();
        iClassesService.remove(queryWrapper);*/

        //classesList和listAll比对后删除不在classesList里的数据

        //如果班级classesList有数据，我们进行跟新，如果id不为空跟新，如果id为空是新增
        classesList.forEach(classes->{
            iClassesService.saveOrUpdate(classes);
        });
        return iClassesService.list();
    }

}
